package com.ndp.fb.mq.service.schedulerservice.adresource;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.ndp.fb.fbagent.service.AdResouceFBService;
import com.ndp.fb.model.AdResourceStats;
import com.ndp.fb.model.fbagent.param.APIPriority;
import com.ndp.fb.model.fbagent.param.ApiCallBackTarget;
import com.ndp.fb.model.fbagent.param.adimage.AdImageParam;
import com.ndp.fb.mongo.api.AccountAdImageMongoService;
import com.ndp.fb.mongo.api.AdImageMongoService;
import com.ndp.fb.mongo.api.AdResourceStatsMongoService;
import com.ndp.fb.mongo.model.Image;
import com.ndp.fb.mq.api.service.schedulerservice.AdAccountsSchedulerService;
import com.ndp.fb.mq.api.service.schedulerservice.AdResourceSchedulerService;
import com.ndp.fb.mq.service.schedulerservice.thirdpictureaudit.AutoCheckConstant;
import com.ndp.fb.rdb.api.BusinessManagerRdbService;
import com.ndp.fb.rdb.api.FbUserRdbService;
import com.ndp.fb.rdb.api.UserRdbServices;
import com.ndp.fb.util.ThreadPool;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by infi.he on 2015/4/8.
 */
@Service
public class AdResourceSchedulerServiceImpl implements AdResourceSchedulerService {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Reference
    private UserRdbServices userRdbServices;
    @Reference
    private AdResouceFBService adResouceFBService;
    @Reference
    private FbUserRdbService fbUserRdbService;
    @Reference
    private BusinessManagerRdbService businessManagerService;

    @Reference
    private AdResourceStatsMongoService adResourceStatsMongoService;
    @Reference
    private AdAccountsSchedulerService adaccountsSchedulerService;

    @Reference
    private AdImageMongoService adImageMongoService;
    @Reference
    private AccountAdImageMongoService accountAdImageMongoService;


    @Override
    public void getImageHash(String bug) {
        ThreadPool.execute(() -> {
            List<AdResourceStats> adResourceStatsList = adResourceStatsMongoService.getAdResourceImageHashIsNull();
            if (CollectionUtils.isNotEmpty(adResourceStatsList)) {
                for (AdResourceStats adResourceStats : adResourceStatsList) {
                    try {
                        AdImageParam requestParam = new AdImageParam();
                        requestParam.setFbAccountId(AutoCheckConstant.getFbAccountId());
                        String token = adaccountsSchedulerService.getAdaccountsToken(requestParam.getFbAccountId());
                        if (StringUtils.isNotEmpty(token)) {
                            requestParam.setAccessToken(token);
                            requestParam.setNfsFilePath(adResourceStats.getVisitPath());
                            requestParam.setFileName(adResourceStats.getVisitPath());
                            requestParam.setApiPriorityCode(APIPriority.UploadImageAsyn.getCode());
                            requestParam.setApiCallbackTargetType(ApiCallBackTarget.PublishResource.GetImageHash.getTargetType());
                            requestParam.setCallBack(true);
                            Map<String, String> equipment = new HashMap<>();
                            equipment.put("type", "1");
                            equipment.put("mongodbId", adResourceStats.getMongodbId());
                            requestParam.setEquipment(equipment);
                            adResouceFBService.uploadAdImages(requestParam);
                        }
                    } catch (Exception e) {
                        logger.error("计算图片{}的imagehash出错", adResourceStats.getMd5());
                        logger.error(e.getMessage(), e);
                    }


                }

            }
        });

        ThreadPool.execute(() -> {
            List<Image> images = adImageMongoService.findHashIsNull();
            if (CollectionUtils.isNotEmpty(images)) {
                for (Image image : images) {
                    try {
                        if(StringUtils.isNotBlank(image.getMd5())){
                            String hash = adResourceStatsMongoService.getImageHashbyMd5(image.getMd5());
                            if(StringUtils.isBlank(hash)){
                                hash = accountAdImageMongoService.getImageHashbyMd5(image.getMd5());
                            }
                            if(StringUtils.isNotBlank(hash)){
                                image.setHash(hash);
                                adImageMongoService.upsertAdImage(image);
                                continue;
                            }

                        }
                        AdImageParam requestParam = new AdImageParam();
                        requestParam.setFbAccountId(AutoCheckConstant.getFbAccountId());
                        String token = adaccountsSchedulerService.getAdaccountsToken(requestParam.getFbAccountId());
                        if (StringUtils.isNotEmpty(token)) {
                            requestParam.setAccessToken(token);
                            if (StringUtils.isNotBlank(image.getPicture())) {
                                requestParam.setNfsFilePath(image.getPicture());
                                requestParam.setFileName(image.getPicture().split("\\?")[0]);
                                requestParam.setApiPriorityCode(APIPriority.UploadImageAsyn.getCode());
                                requestParam.setApiCallbackTargetType(ApiCallBackTarget.PublishResource.GetImageHash.getTargetType());
                                requestParam.setCallBack(true);
                                Map<String, String> equipment = new HashMap<>();
                                equipment.put("type", "2");
                                equipment.put("md5", image.getMd5());
                                equipment.put("picture", image.getPicture());
                                requestParam.setEquipment(equipment);
                                adResouceFBService.uploadAdImages(requestParam);
                            }

                        }
                    } catch (Exception e) {
                        logger.error("计算图片{}的imagehash出错,URL:{}", image.getMd5(), image.getPicture());
                        logger.error(e.getMessage(), e);
                    }


                }

            }
        });

    }

}
